/*
* Copyright© 2018 Shanxi Lu'an Taihang Laihui Net Tech co.,LTD.
*/
package com.laihuichuxing.netty.server.server.scanner;

import com.laihuichuxing.netty.common.core.annotion.SocketCommand;
import com.laihuichuxing.netty.common.core.annotion.SocketModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Description: handler扫描器
 *
 * @author YangGuang
 * @since: 1.0
 * Create Date Time: 2018/7/4 17:27
 * Update Date Time:
 * @see
 */
@Component
public class HandlerScaner implements BeanPostProcessor {

    private Logger logger = LoggerFactory.getLogger(HandlerScaner.class);

    public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
        return o;
    }

    public Object postProcessAfterInitialization(Object bean, String s) throws BeansException {
        Class<? extends Object> clazz = bean.getClass();
        Class<?>[] interfaces = clazz.getInterfaces();
        if(interfaces != null && interfaces.length > 0){
            //扫描类的所有接口父类
            for (Class<?> interFace : interfaces) {
                //判断是否为handler接口类
                SocketModule socketModule = interFace.getAnnotation(SocketModule.class);
                if (socketModule == null) {
                    continue;
                }

                //找出命令方法
                Method[] methods = interFace.getMethods();
                if(methods != null && methods.length > 0){
                    for(Method method : methods){
                        SocketCommand socketCommand = method.getAnnotation(SocketCommand.class);
                        if(socketCommand == null){
                            continue;
                        }

                        final short module = socketModule.module();
                        final short cmd = socketCommand.cmd();

                        if(InvokerHoler.getInvoker(module, cmd) == null){
                            InvokerHoler.addInvoker(module, cmd, Invoker.valueOf(method, bean));
                        }else{
                            logger.warn("重复命令:module:{},cmd:{}",module,cmd);
                        }
                    }
                }

            }
        }
        return bean;
    }
}
